const path = require('path');
const sqlite3 =  require('sqlite3').verbose();
import moment from "moment"


const isBuild = process.env.NODE_ENV === 'production'

const pathToDbFile = path.join(
  isBuild ? __dirname : __static,'../src/db/qdjxjy.db',
)
/***
 * 插入
 * @param pid appUuid
 * @param courseId 课程
 * @param chapterId 章节
 */
export function insert (pid ,courseId,chapterId) {

  // const sqlite3 = window.require('sqlite3').verbose();
  let db = new sqlite3.Database(pathToDbFile)
  let time = moment().format('YYYY-MM-DD HH:mm:ss')
  console.log(pid ,courseId,chapterId,time);



  db.serialize(()=> {
    db.run("insert into log (pid, courseId,chapterId,time) values (?, ?, ? ,?)", [pid ,courseId,chapterId,time], function (err, res) {
      console.log("insert callback:", err, res, this.lastID);
    });
  });
}


/***
 * 删除pid相关的数据
 * @param pid
 */
export function deletePid(pid){

  return new Promise((resolve, reject) => {
    // const sqlite3 = window.require('sqlite3').verbose();
    let db = new sqlite3.Database(pathToDbFile)
    console.log(pid);

    db.run("delete from log where pid=?", pid, function (err, res) {
      console.log("delete callback", err, res, this.changes, this.lastID);
      resolve( err, res, this.changes, this.lastID);
    });

  })
}

/***
 * 删除 章节
 */
export function deleteChapter(pid ,courseId,chapterId){

  return new Promise((resolve, reject) => {
    // const sqlite3 = window.require('sqlite3').verbose();
    let db = new sqlite3.Database(pathToDbFile)

    db.run("delete from log where pid=? and courseId=? and chapterId=?", [pid ,courseId,chapterId], function (err, res) {
      console.log("deleteChapter callback", err, res, this.changes, this.lastID);
      resolve( err, res, this.changes, this.lastID);
    });

  })
}

/***
 * 删除所有
 * @param pid
 */
export function deleteAll(){

  return new Promise((resolve, reject) => {
    // const sqlite3 = window.require('sqlite3').verbose();
    let db = new sqlite3.Database(pathToDbFile)

    db.run("delete from log ", [], function (err, res) {
      console.log("deleteAll callback", err, res, this.changes, this.lastID);
      resolve( err, res, this.changes, this.lastID);
    });

  })
}
/***
 * 查询所有
 * @returns {Promise<unknown>}
 */
export function queryALl(){

  return new Promise((resolve, reject) => {
    // const sqlite3 = window.require('sqlite3').verbose();
    let db = new sqlite3.Database(pathToDbFile)
// 返回所有数据
    db.all('SELECT * FROM log', function (err, row) {
      resolve(row);
    });

  });
}

